//
//  ServiceViewController.m
//  KaNongJia
//
//  Created by RYX on 2018/12/19.
//  Copyright © 2018 tuobu. All rights reserved.
//

#import "ServiceViewController.h"
#import <WebsocketStompKit/WebsocketStompKit.h>
#import "ChatModel.h"
#import "DataManager.h"
#import "UserModel.h"
#import "HomeList.h"
#import "BottomView.h"
#import "ChatList.h"
#import "ChatStore.h"
#import "BGFMDB.h"
#import "STOMPClientManager.h"
#import "CJUserCell.h"
#import "CJServiceCell.h"
#import "MarqueeLabel.h"

#define ServiceOnLine @"您好,请问有什么可以帮助您的？"
#define ServiceNotOnLine @"客服暂不在线,您可以留言"

@interface ServiceViewController ()<UITableViewDelegate,UITableViewDataSource,BottomViewDelegate>

@property (nonatomic, strong) STOMPClient *client;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *listArr;
@property (nonatomic,strong) BottomView *bottomView;

@property (nonatomic,strong) MarqueeLabel *marqueeLa;

@end

@implementation ServiceViewController

- (MarqueeLabel *)marqueeLa{
    
    if (!_marqueeLa) {
        
        _marqueeLa = [[MarqueeLabel alloc] initWithFrame:CGRectZero duration:8.0 andFadeLength:0.0f];
        _marqueeLa.backgroundColor = [UIColor whiteColor];
        _marqueeLa.textColor = UIColor.redColor;
        _marqueeLa.font = [UIFont systemFontOfSize:13];
    }
    
    return _marqueeLa;
}

- (BottomView *)bottomView{

    if (!_bottomView) {

        _bottomView = [[BottomView alloc] init];
        _bottomView.delegate = self;
    }
    return _bottomView;
}

- (NSMutableArray *)listArr{

    if (!_listArr) {

        _listArr = [NSMutableArray array];

    }

    return _listArr;
}

- (UITableView *)tableView{

    if (!_tableView) {

        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 75;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.5)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[CJServiceCell class] forCellReuseIdentifier:@"ServiceCell"];
        [_tableView registerClass:[CJUserCell class] forCellReuseIdentifier:@"UserCell"];
    }

    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
    
    [ChatList sharedInstance].isChatVC = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
    [ChatList sharedInstance].isChatVC = NO;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithHexString:@"#EBEBEB"];
    
    [self setUI];
    
    //获取本地缓存消息记录
    [self getChatList];

    //请求Api获取遗漏消息
    [self getNoReadInfo];
    
    //连接WebStoket
    [self setWebStoket];
    
    //判断客服是否在线
    [self serviceIfOnline];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - 获取未读消息
- (void)getNoReadInfo{
    
    NSArray *listArr = [[NSMutableArray alloc] initWithArray:[ChatModel bg_findAll:CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue])]];
    ChatModel *lastFMDBModel = listArr.lastObject;
    
    ChatStore *store = [[ChatStore alloc] init];
    MJWeakSelf
    
    UserModel *model = [HomeList sharedInstance].userModel;
    NSString *sign = [NSString stringWithFormat:@"%@-%@",model.realName,model.phoneNumber];
    
    [store searchNoReadMsgWithCustomerSign:sign Sucess:^(NSArray *arr) {
        
        if (arr.count > 0) {
            
            ChatModel *lastModel = arr.lastObject;
            
            if (![lastModel.sign isEqualToString:lastFMDBModel.sign]) {
                
                for (ChatModel *model in arr) {
                    
                    model.name = @"客服";
                    model.type = ChatTypeService;
                    model.img = @"kefuImg";
                    model.bg_tableName = CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue]);
                    [model bg_save];
                    
                    weakSelf.listArr = [[NSMutableArray alloc] initWithArray:[ChatModel bg_findAll:CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue])]];
                    [weakSelf.tableView reloadData];
                }
            }
        }
        
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}
#pragma mark - 判断客服是否在线
- (void)serviceIfOnline{
    
    ChatStore *store = [[ChatStore alloc] init];
    
    MJWeakSelf
    [store serviceOnlineSuccess:^(BOOL onLine,NSString *tip) {
        
        NSString *tt = [NSString stringWithFormat:@"系统提示：%@",tip];
        self.marqueeLa.text = [NSString stringWithFormat:@"%@                                                      %@                                                      ",tt,tt];

//        [weakSelf showMBPError:tip];
        
        if (onLine) {
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            NSDate *currentDate = [NSDate date];
            NSString *currentDateString = [formatter stringFromDate:currentDate];
            
            NSArray *arr = [[NSMutableArray alloc] initWithArray:[ChatModel bg_find:CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue]) type:bg_createTime dateTime:currentDateString]];
            
            BOOL ifHadOnline24Hour = YES;
            for (ChatModel *model in arr) {
                
                if ([model.content isEqualToString:ServiceOnLine]) {
                    
                    ifHadOnline24Hour = NO;
                    break;
                }
            }
            
            ChatModel *lastModel = arr.lastObject;
            if (ifHadOnline24Hour || [lastModel.content isEqualToString:ServiceNotOnLine]) {
                
                NSString *sign = [NSString stringWithFormat:@"service-%@",[StrTool currentTimeStr]];
                [self addMsgWithType:ChatTypeService andMsg:ServiceOnLine andSign:sign];
            }
            
        }else{
            
            NSMutableArray *arr = [[NSMutableArray alloc] initWithArray:[ChatModel bg_findAll:CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue])]];
            ChatModel *model = arr.lastObject;
            if (![model.content isEqualToString:ServiceNotOnLine]) {
                
                NSString *sign = [NSString stringWithFormat:@"service-%@",[StrTool currentTimeStr]];
                [weakSelf addMsgWithType:ChatTypeService andMsg:ServiceNotOnLine andSign:sign];
            }
        }
    } Failure:^(NSError *error) {
        
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
}

- (void)keyboardWillChangeFrame:(NSNotification *) note {

    // 1.取得弹出后的键盘frame
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    // 2.键盘弹出的耗时时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    // 3.键盘变化时，view的位移，包括了上移/恢复下移
    CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;

    [UIView animateWithDuration:duration animations:^{

        self.tableView.transform = CGAffineTransformMakeTranslation(0, transformY);
        self.bottomView.transform = CGAffineTransformMakeTranslation(0, transformY);
    }];
}

#pragma mark - 获取历史聊天记录
- (void)getChatList{

    self.listArr = [[NSMutableArray alloc] initWithArray:[ChatModel bg_findAll:CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue])]];
    [self.tableView reloadData];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self scrollToBottom:NO];
    });
    
}

- (void)setUI{

    ViewHeader *header = [[ViewHeader alloc] initWithtTitle:@"在线客服" andRirhtBtn:@"垃圾"];
    
    MJWeakSelf
    [header setRightBtnBlock:^(UIButton * btn) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"清空当前聊天记录？" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [ChatModel bg_delete:CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue]) where:nil];
            weakSelf.listArr = [[NSMutableArray alloc] initWithArray:[ChatModel bg_findAll:CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue])]];
            [weakSelf.tableView reloadData];
            
        }]];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:header];

    [self.view addSubview:self.marqueeLa];
    
    [self.view addSubview:self.bottomView];

    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.height.mas_offset(TAB_BAR_HEIGHT);
        make.left.bottom.right.equalTo(self.view);

    }];

    [self.marqueeLa mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_offset(25);
        make.left.right.equalTo(self.view);
        make.top.equalTo(header.mas_bottom);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.marqueeLa.mas_bottom).offset(1);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];

}

#pragma mark - 连接
- (void)setWebStoket{
    
    [[STOMPClientManager sharedInstance] clientContent];

    [[STOMPClientManager sharedInstance] setBlock:^(NSString *body) {

        NSRange startRange = [body rangeOfString:@"content\":"];
        NSRange endRange = [body rangeOfString:@",\"from"];
        
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        NSString *result = [body substringWithRange:range];
        DLog(@"xxxxxx==%@",result);
        
        if ([result isEqualToString:@"null"]) {
            
            //客户端发送消息收到回执
            NSRange typeStartRange = [body rangeOfString:@"type\":"];
            NSRange typeEndRange = [body rangeOfString:@"}"];
            
            NSRange typeRange = NSMakeRange(typeStartRange.location + typeStartRange.length, typeEndRange.location - typeStartRange.location - typeStartRange.length);
            NSString *typeResult = [body substringWithRange:typeRange];
            DLog(@"xxxxxx==%@",typeResult);
            
            if (![typeResult isEqualToString:@"1"]) {
                
                //消息发送失败。调用api重新发送到服务器
                //代码部分
                
                
            }
            
        }else{
            
            //接收服务器发来的消息
            NSString *str = [result stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            
            NSRange signStartRange = [body rangeOfString:@"sign\":\""];
            NSRange signEndRange = [body rangeOfString:@"\",\"type"];
            NSRange signRange = NSMakeRange(signStartRange.location + signStartRange.length, signEndRange.location - signStartRange.location - signStartRange.length);
            NSString *signResult = [body substringWithRange:signRange];
            
            [self addMsgWithType:ChatTypeService andMsg:str andSign:signResult];
            
            MJWeakSelf
            if (![ChatList sharedInstance].isChatVC) {
                
                //用户不在聊天界面界面,记录下未读消息的sign
                [[ChatList sharedInstance].noReadMsgArr addObject:signResult];
                
                //通知首页未读消息数增加
                
            }else{
                
                //告知服务器消息此条消息已读
                ChatStore *store = [[ChatStore alloc] init];
                [store notiServerHadReadInfoWithSign:signResult Success:^{
                
                    
                } Failure:^(NSError *error) {
                   
                    [weakSelf showMBPError:[HttpTool handleError:error]];
                }];
            }
        }

    }];

}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    ChatModel *model = self.listArr[indexPath.row];
    
    if (model.type == ChatTypeService) {
        
        CJServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ServiceCell"];
        cell.backgroundColor = UIColor.clearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
        
    }else{
        
        CJUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserCell"];
        cell.backgroundColor = UIColor.clearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }
    

}

- (void)addMsgWithType:(NSInteger)type andMsg:(NSString *)msg andSign:(NSString *)sign{

    if (type == ChatTypeUser) {

        UserModel *currentUser = [HomeList sharedInstance].userModel;

        ChatModel *model = [[ChatModel alloc] init];
        model.name = currentUser.realName;
        model.type = ChatTypeUser;
        model.img = currentUser.headImage;
        model.content = msg;

        model.bg_tableName = CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue]);
        [model bg_save];
        
    }else{

        ChatModel *model = [[ChatModel alloc] init];
        model.name = @"客服";
        model.type = ChatTypeService;
        model.img = @"kefuImg";
        model.content = msg;
        
        model.bg_tableName = CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue]);
        [model bg_save];
        
    }
    
    self.listArr = [[NSMutableArray alloc] initWithArray:[ChatModel bg_findAll:CHATTAB([[UserDefaultsManager sharedInstance].user_id intValue])]];
    [self.tableView reloadData];
    
    [self scrollToBottom:NO];
}


#pragma mark - BottomViewDelegate
- (void)onKeyBoardReturnBtnWithMsg:(NSString *)msg {

//    if (self.listArr.count <= 4) {
//
//        [self.view endEditing:YES];
//    }
    
    [[STOMPClientManager sharedInstance] sendMsg:msg];

    UserModel *model = [HomeList sharedInstance].userModel;
    NSString *sign = [NSString stringWithFormat:@"%@-%@",model.realName,model.phoneNumber];
    [self addMsgWithType:ChatTypeUser andMsg:msg andSign:sign];

    self.bottomView.tf.text = @"";

}


#pragma mark - 滚动到最底部
-(void)scrollToBottom:(BOOL)animated {
    
    if (self.listArr.count <= 0) {
        
        return;
    }
    
    NSUInteger rowCount = [self.tableView numberOfRowsInSection:0];
    
    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:rowCount-1 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}


@end
